import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/event_bus_util/eventbus_util.dart';
import 'package:yt_devops/components/format_util.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/text_width.dart';
import 'package:yt_devops/components/timer_picker.dart';
import 'package:yt_devops/components/tips.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/new_air_cooling_page/component/char_x.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_mains_elec_detail/keep_aliver_wrapper.dart';
import 'package:yt_devops/pages/site/site_statis_data/show_full_screen_btn.dart';
import 'package:yt_devops/pages/site/site_statis_data/site_statis_data_model.dart';
import 'package:yt_devops/pages/site/widgets/electricity_statistics_chart.dart';
import 'package:yt_devops/pages/site/widgets/full_screen_power_chart.dart';
import 'package:yt_devops/pages/site/widgets/power_rank_tab.dart';
import 'package:yt_devops/pages/site/widgets/profit_chart.dart';
import 'package:yt_devops/pages/site/widgets/site_power_rank_widget.dart';
import 'package:yt_devops/pages/site/widgets/statistics_itme_widget.dart';
import 'package:yt_devops/pages/site/widgets/statistics_time_unit_tab.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/site/site_services.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';

import 'full_screen_profit_chart.dart';
import 'package:dart_date/dart_date.dart';

///
/// @Description TODO
/// @Author liuer
/// @CreateTime 2024年03月27日 08:49
class HomeStatistics extends StatefulWidget {
  const HomeStatistics({super.key});

  @override
  State<HomeStatistics> createState() => _HomeStatisticsState();
}

class _HomeStatisticsState extends State<HomeStatistics>
    with TickerProviderStateMixin {
  DateTimePickerMode pickerMode = DateTimePickerMode.day;
  StatisticUnitStatusType statisticUnitStatusType = StatisticUnitStatusType.day;
  bool isChooseAccumulate = false;
  String charge = '--';
  String discharge = '--';
  String chargeCost = '--';
  String dischargeIncome = '--';
  String gain = '--';
  String chooseDate = '';
  DateTime selectedDate = DateTime.now();
  String rankTitle = '';
  PowerRankTabType type = PowerRankTabType.electricity; // 默认充电功率
  ///底部排名的tab
  PowerRankTabType rankType = PowerRankTabType.power;
  SiteServices siteServices = SiteServices();
  Map<String, dynamic> commonMap = {};
  List<dynamic> rankList = [];
  GlobalKey electricityChartKey = GlobalKey();
  GlobalKey revenueChartKey = GlobalKey();
  StreamSubscription? scripttion;
  final SiteStatisDataModel state = SiteStatisDataModel();

  late TabController tabController;
  List timeList = ChartXDate.getData(timeInterval: 5);
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  bool isLoading = false;
  List electricityBarChartList = []; //电量
  List barProfitList = []; //收益
  // List<Map<String, dynamic>> showElectricityTitles = [];
  List eChartElectricityShowList = []; //展示的电量
  final GlobalKey electricityTitlesKey = GlobalKey();
  double showElectricityHeight = 15;
  // num profitMaxValue = 1;
  // num profitMinValue = 0;
  // num electricityMaxValue = 1;
  // num electricityMinValue = 0;
  List<dynamic> electricityXAxisList = []; //电量x轴数据
  List<dynamic> profitXAxisList = []; //功率x轴数据
  // List<num> electricityMaxMinList = []; //电量最大最小值
  // List<num> profitMaxMinList = []; //电量最大最小值
  @override
  void initState() {
    Log.d('HomeStatistics==');
    // TODO: implement initState
    super.initState();
    // initPowerData();
    tabController = TabController(length: 2, vsync: this);
    rankTitle = ResKey.dailySiteRanking.tr;
    chooseDate = DateTime.now().toString().substring(0, 10);
    selectedDate = DateTime.now();
    electricityXAxisList = ChartXDate.getHoursData();
    profitXAxisList = ChartXDate.getHoursData();
    getAllData();
    scripttion =
        EventBusUtil.getInstance().on<SwitchLanguage>().listen((event) {
      Log.d('SwitchLanguage==');
      if (pickerMode == DateTimePickerMode.day) {
        rankTitle = ResKey.dailySiteRanking.tr;
      } else if (pickerMode == DateTimePickerMode.month) {
        pickerMode = DateTimePickerMode.month;
        rankTitle = ResKey.monthlySiteRanking.tr;
      } else if (pickerMode == DateTimePickerMode.year) {
        rankTitle = ResKey.annualSiteRanking.tr;
      } else {
        rankTitle = ResKey.accumulatedSiteRanking.tr;
      }
      getAllData();
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    scripttion?.cancel();
    tabController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: 224.h,
          width: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage(ImageAssets.headerBg),
              fit: BoxFit.cover,
            ),
          ),
        ),
        Container(
          margin: EdgeInsets.only(top: ScreenUtil().statusBarHeight + 40 + 15),
          decoration: const BoxDecoration(
              color: Colour.backgroundColor,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(8), topRight: Radius.circular(8))),
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.only(
                  left: 16.w,
                  right: 16.w,
                  top: 16,
                ),
                decoration: const BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(8))),
                child: Column(
                  children: [
                    /// 时间选择器
                    Visibility(
                      visible: !isChooseAccumulate,
                      child: KeepAliveWrapper(
                        YtTimePicker(
                          pickerMode: DateTimePickerMode.all,
                          initialDateTime: selectedDate,
                          onChange: (date, StatisticUnitStatusType? tabMode) =>
                              changeData(date, tabMode),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: SmartRefresher(
                    controller: refreshController,
                    enablePullDown: true,
                    enablePullUp: false,
                    header: ListTips.classicHeader,
                    onRefresh: () => onRefresh(),
                    child: ListView(
                      padding: EdgeInsets.zero,
                      children: [
                        Container(
                            margin: EdgeInsets.only(
                                left: 16.w, right: 16.w, top: 10, bottom: 10),
                            decoration: const BoxDecoration(
                                color: Colors.white,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(8))),
                            child: Column(children: [
                              Container(
                                // height: 40,
                                padding: EdgeInsets.only(
                                    left: 16.w, top: 16, bottom: 10),
                                // color: Colors.white,
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  ResKey.dataBoard.tr,
                                  style: ytTextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w500),
                                ),
                              ),
                              dataOverview(),
                            ])),
                        Container(
                            margin: EdgeInsets.only(
                                bottom: 10, left: 16.w, right: 16),
                            padding: const EdgeInsets.only(top: 16),
                            decoration: const BoxDecoration(
                                color: Colors.white,
                                borderRadius:
                                    BorderRadius.all(Radius.circular(8))),
                            child: Column(children: [
                              Container(
                                color: Colors.white,
                                child: PowerRankTab(
                                  type,
                                  (PowerRankTabType tabType) {
                                    setState(() {
                                      type = tabType;
                                      Log.d('tabType==' +
                                          tabType.index.toString());
                                      // state.showElectricityTitles.clear();
                                      tabController
                                          .animateTo(tabType.index - 1);
                                      _updateTitleHeight();
                                    });
                                  },
                                  string1: '',
                                  string2: ResKey.quantityOfElectricity.tr,
                                  string3: ResKey.income.tr,
                                ),
                              ),
                              Row(
                                children: [
                                  const Spacer(),
                                  ShowFullScreenBtn(
                                    onTap: () {
                                      if (type == PowerRankTabType.profit) {
                                        Navigator.push(
                                          Get.context!,
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  FullScreenProfitChart(
                                                      data: barProfitList,
                                                      timeList:
                                                          electricityXAxisList,
                                                      // maxValue: profitMaxValue,
                                                      // minValue: profitMinValue,
                                                      tooltipFormatter: FormatUtil
                                                          .getToolTipFormater(
                                                              timeType:
                                                                  statisticUnitStatusType,
                                                              selectedType:
                                                                  type,
                                                              chartType: 1,
                                                              time:
                                                                  selectedDate),
                                                      paramList:
                                                          state.paramList)),
                                        );
                                      } else if (type ==
                                          PowerRankTabType.electricity) {
                                        Navigator.push(
                                          Get.context!,
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  FullScreenPowerChart(
                                                      data:
                                                          eChartElectricityShowList,
                                                      timeList:
                                                          electricityXAxisList,
                                                      tooltipFormatter: FormatUtil
                                                          .getToolTipFormater(
                                                              timeType:
                                                                  statisticUnitStatusType,
                                                              selectedType:
                                                                  type,
                                                              chartType: 2,
                                                              time:
                                                                  selectedDate),
                                                      paramList:
                                                          state.paramList)),
                                        );
                                      }
                                    },
                                  )
                                ],
                              ),
                              Container(
                                height: type == PowerRankTabType.electricity
                                    ? 260 + showElectricityHeight + 20
                                    : 310,
                                decoration: const BoxDecoration(
                                    color: Colors.white,
                                    borderRadius:
                                        BorderRadius.all(Radius.circular(8))),
                                child: TabBarView(
                                    controller: tabController,
                                    physics:
                                        const NeverScrollableScrollPhysics(),
                                    children: [
                                      Container(
                                          margin:
                                              const EdgeInsets.only(bottom: 10),
                                          // height: 230,
                                          color: Colors.white,
                                          child: Column(children: [
                                            Container(
                                              height: 260,
                                              margin: const EdgeInsets.only(
                                                  top: 0, bottom: 5),
                                              color: Colors.white,
                                              child: ElectricityStatisticsChart(
                                                key: electricityChartKey,
                                                timeList: electricityXAxisList,
                                                // maxValue: electricityMaxValue,
                                                // minValue: electricityMinValue,
                                                data: eChartElectricityShowList,
                                                paramList: state.paramList,
                                                tooltipFormatter: FormatUtil
                                                    .getToolTipFormater(
                                                        timeType:
                                                            statisticUnitStatusType,
                                                        selectedType: type,
                                                        chartType: 1,
                                                        time: selectedDate),
                                              ),
                                            ),
                                            _electricityTypeWidget()
                                          ])),
                                      Container(
                                          margin: const EdgeInsets.only(
                                              top: 0, bottom: 10),
                                          height: 230,
                                          color: Colors.white,
                                          child: ProfitChart(
                                              key: revenueChartKey,
                                              profit: barProfitList,
                                              timeList: electricityXAxisList,
                                              // maxValue: profitMaxValue,
                                              // minValue: profitMinValue,
                                              tooltipFormatter:
                                                  FormatUtil.getToolTipFormater(
                                                      timeType:
                                                          statisticUnitStatusType,
                                                      selectedType: type,
                                                      chartType: 2,
                                                      time: selectedDate),
                                              // dischargeIncome:
                                              //     dischargeIncomeData,
                                              paramList: state.paramList)),
                                    ]),
                              )
                            ])),
                        Container(
                          margin: EdgeInsets.only(
                              left: 16.w, right: 16.w, bottom: 10),
                          decoration: const BoxDecoration(
                              color: Colors.white,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8))),
                          child: SitePowerRankWidget(
                              title: rankTitle,
                              rankList: rankList,
                              type: rankType,
                              typeCallBack: (PowerRankTabType type) {
                                Log.d('changeType===$type');
                                rankType = type;
                                getEsPowerStatisticsRank();
                                setState(() {});
                              }),
                        ),
                      ],
                    )),
              )
            ],
          ),
        )
      ],
    );
  }

  getAllData() {
    commonMap = {
      'type': statisticUnitStatusType.value,
      'date': chooseDate,
      'subType': 1
    };
    getOverviewStatistics();
    getEsPowerStatisticsRank();
    loadSiteDataStatistics(commonMap);
  }

  loadSiteDataStatistics(params) async {
    if(!isLoading)showLoading(toast: ResKey.loading.tr);
    var data =
        await siteServices.getSiteDataStatisticsNew(params, onError: (error) {
      dismissLoading();
      refreshController.loadComplete();
      refreshController.refreshCompleted();
      showError(error.message.toString());
      return false;
    });
    dismissLoading();
    isLoading = true;
    if (data != null) {
      electricityBarChartList.clear();
      eChartElectricityShowList.clear();
      state.showElectricityTitles.clear();
      profitXAxisList.clear();
      if (data['mainsUse'] != null) {
        Map map = data['mainsUse'];
        if (map['flag'] != null && map['flag'] == true) {
          _addElectricityBarEChartData(map['name'].toString(),
              _handleBarData(map['data'] ?? [], statisticUnitStatusType.value),
              colorString: map['color'] ?? '#FAC958');
        }
      }
      if (data['pvSelfUse'] != null) {
        Map map = data['pvSelfUse'];
        if (map['flag'] != null && map['flag'] == true) {
          _addElectricityBarEChartData(map['name'].toString(),
              _handleBarData(map['data'] ?? [], statisticUnitStatusType.value),
              colorString: map['color'] ?? '#FAC958');
        }
      }
      if (data['pvPowerGeneration'] != null) {
        Map map = data['pvPowerGeneration'];
        if (map['flag'] != null && map['flag'] == true) {
          _addElectricityBarEChartData(map['name'].toString(),
              _handleBarData(map['data'] ?? [], statisticUnitStatusType.value),
              colorString: map['color'] ?? '#FAC958');
        }
      }
      if (data['essCharge'] != null) {
        Map map = data['essCharge'];
        if (map['flag'] != null && map['flag'] == true) {
          _addElectricityBarEChartData(map['name'].toString(),
              _handleBarData(map['data'] ?? [], statisticUnitStatusType.value),
              colorString: map['color'] ?? '#FAC958');
        }
      }
      if (data['essDischarge'] != null) {
        Map map = data['essDischarge'];
        if (map['flag'] != null && map['flag'] == true) {
          _addElectricityBarEChartData(map['name'].toString(),
              _handleBarData(map['data'] ?? [], statisticUnitStatusType.value),
              colorString: map['color'] ?? '#FAC958');
        }
      }
      if (data['loadUse'] != null) {
        Map map = data['loadUse'];
        if (map['flag'] != null && map['flag'] == true) {
          _addElectricityBarEChartData(map['name'].toString(),
              _handleBarData(map['data'] ?? [], statisticUnitStatusType.value),
              colorString: map['color'] ?? '#FAC958');
        }
      }
      if (data['gain'] != null) {
        barProfitList.clear();
        Map map = data['gain'];
        // Log.d('gain=== + ' + map.toString());
        if (map['flag'] != null && map['flag'] == true) {
          _addElectricityBarEChartData(map['name'].toString(),
              _handleBarData(map['data'] ?? [], statisticUnitStatusType.value),
              colorString: map['color'] ?? '#FAC958', isProfit: true);
        }
      }
    }
    eChartElectricityShowList = List.from(electricityBarChartList);
    setState(() {});
    _updateTitleHeight();
  }

  _updateTitleHeight() {
    Future.delayed(const Duration(milliseconds: 200), () {
      if (electricityTitlesKey.currentContext != null) {
        showElectricityHeight =
            electricityTitlesKey.currentContext!.size!.height;
        Log.d('showElectricityHeight==' + showElectricityHeight.toString());
        setState(() {});
      }
    });
  }

  _handleBarData(List? data, String statisticUnitStatusTypeString) {
    List result = [];
    if (data != null) {
      for (var element in data!) {
        String time = element['eventTs'].toString();
        if (statisticUnitStatusTypeString ==
                StatisticUnitStatusType.day.value &&
            element['eventTs'].toString().length > 16) {
          time = element['eventTs'].toString().substring(10, 16);
        } else if (statisticUnitStatusTypeString ==
                StatisticUnitStatusType.month.value &&
            element['eventTs'].toString().length >= 10) {
          time = element['eventTs'].toString().substring(8, 10);
        } else if (statisticUnitStatusTypeString ==
                StatisticUnitStatusType.year.value &&
            element['eventTs'].toString().length >= 7) {
          time = element['eventTs'].toString().substring(5, 7);
        }
        // List temp = [
        //   time,
        //   element['doubleVal'] != null ? element['doubleVal'].toString() : '--'
        // ];
        result.add(element['doubleVal'] != null
            ? element['doubleVal'].toString()
            : '--');
      }
    }
    return result;
  }

  ///获取储能概览
  getOverviewStatistics() async {
    // if (isLoading == false) showLoading(toast: ResKey.loading.tr);
    var result = await siteServices.getSiteOverviewGainsStatistics({
      'time': commonMap['date'],
      'type': commonMap['type'],
    }, onError: (error) {
      // dismissLoading();
      isLoading = true;
      refreshController.refreshCompleted();
      handleException(error);
      return false;
    });
    // dismissLoading();
    refreshController.refreshCompleted();
    if (result != null) {
      setState(() {
        if (result['storageChargeElec'] != null) {
          charge = result['storageChargeElec'].toString();
        } else {
          charge = '--';
        }
        if (result['storageDischargeElec'] != null) {
          discharge = result['storageDischargeElec'].toString();
        } else {
          discharge = '--';
        }
        if (result['storageCharge'] != null) {
          chargeCost = result['storageCharge'].toString();
        } else {
          chargeCost = '--';
        }
        if (result['storageDischarge'] != null) {
          dischargeIncome = result['storageDischarge'].toString();
        } else {
          dischargeIncome = '--';
        }
        if (result['essGains'] != null) {
          gain = result['essGains'].toString();
        } else {
          gain = '--';
        }
      });
    }
  }

  ///获取储能电能统计
  getEsPowerStatisticsRank() async {
    Map<String, dynamic> params = Map.from(commonMap);
    params['sortType'] = rankType.index;
    Log.d('params:$params');
    // if (isLoading == false) showLoading(toast: ResKey.loading.tr);
    var result =
        await siteServices.getEsPowerStatisticsRank(params, onError: (error) {
      // dismissLoading();
      handleException(error);
      return false;
    });
    // dismissLoading();
    Log.d('getEsPowerStatisticsRank:$result');
    if (result != null) {
      rankList.clear();
      rankList = result;
      setState(() {});
    }
  }

  changeData(DateTime date, StatisticUnitStatusType? tabMode) {
    Log.d('date==$tabMode');
    selectedDate = date;
    chooseDate = date.toString().substring(0, 10);
    commonMap = {'type': statisticUnitStatusType.value, 'date': chooseDate};
    if (tabMode == StatisticUnitStatusType.day) {
      rankTitle = ResKey.dailySiteRanking.tr;
      electricityXAxisList = ChartXDate.getHoursData();
    } else if (tabMode == StatisticUnitStatusType.month) {
      rankTitle = ResKey.monthlySiteRanking.tr;
      electricityXAxisList = ChartXDate.getMonthData();
    } else if (tabMode == StatisticUnitStatusType.year) {
      rankTitle = ResKey.annualSiteRanking.tr;
      electricityXAxisList = ChartXDate.getYearData();
    } else {
      rankTitle = ResKey.accumulatedSiteRanking.tr;
      electricityXAxisList = ChartXDate.getTotalData();
    }
    statisticUnitStatusType = tabMode!;
    setState(() {});
    getAllData();
  }

  onRefresh() {
    getAllData();
  }

  ///展示或者隐藏电量指标
  hiddenOrShowElectricity(String title) {
    for (var element in state.showElectricityTitles) {
      if (title == element['title']) {
        element['isShow'] = !element['isShow'];
        setState(() {});
      }
    }
    var originMap = {};
    for (int i = 0; i < electricityBarChartList.length; i++) {
      var map = electricityBarChartList[i];
      originMap[map['name']] = map;
    }
    eChartElectricityShowList.clear();
    for (int i = 0; i < state.showElectricityTitles.length; i++) {
      var element = state.showElectricityTitles[i];

      if (element['isShow'] == true) {
        eChartElectricityShowList.add(originMap[element['title']]);
      }
    }
    setState(() {

    });
  }

  _electricityTypeWidget() {
    return
        // ClipRect(child:
        Container(
      key: electricityTitlesKey,
      // height: 80,
      margin: EdgeInsets.only(
        left: 16.w,
        right: 16.w,
      ),
      color: Colors.white,
      child: Wrap(
          direction: Axis.horizontal,
          spacing: 5,
          runSpacing: 5,
          textDirection: TextDirection.ltr,
          children: _getElectricityShowList()),
      // )
    );
    setState(() {

    });
  }

  List<Widget> _getElectricityShowList() {
    List<Widget> list = [];
    if (state.showElectricityTitles.isNotEmpty) {
      for (var element in state.showElectricityTitles) {
        list.add(_powerTypeItem(
            element['title'], element['color'], element['isShow']));
      }
    }
    return list;
  }

  _powerTypeItem(String title, String colorString, bool isShow) {
    Color color = Colour.grayE7Color;
    if (colorString.isNotEmpty && colorString.contains('#')) {
      color = Color(int.parse(colorString.replaceAll('#', '0xFF')));
    }
    var textWidth = TextWidth.calculateTextSize(title, ytTextStyle());
    return MyGestureDetector(
        onTap: () {
          hiddenOrShowElectricity(title);
        },
        child: Container(
          color: Colors.white,
          alignment: Alignment.center,
          width: textWidth + 20,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(1.5),
                  color: isShow ? color : Colour.grayE7Color,
                ),
                height: 3,
                width: 12,
              ),
              const SizedBox(
                width: 5,
              ),
              Text(
                title,
                style: ytTextStyle(),
              ),
            ],
          ),
        ));
  }

  dataOverview() {
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(left: 16.w, right: 16.w, bottom: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Row(
            children: [
              StatisticsItemWidget(
                ResKey.siteSettingObserverStoreChargePower.tr,
                charge,
                'kWh','',
                isHome: true,
              ),
              Gaps.hGap10,
              StatisticsItemWidget(
                ResKey.siteSettingObserverStoreDischargePower.tr,
                discharge,
                'kWh','',
                isHome: true,
              ),
            ],
          ),
          Gaps.vGap10,
          Row(
            children: [
              StatisticsItemWidget(
                'device.storageCharge'.tr,
                chargeCost,
                ResKey.yuan.tr,'',
                isHome: true,
              ),
              Gaps.hGap10,
              StatisticsItemWidget(
                'device.storageDischarge'.tr,
                dischargeIncome,
                ResKey.yuan.tr,'',
                isHome: true,
              ),
            ],
          ),
          Gaps.vGap10,
          StatisticsItemWidget(
            'device.storageRevenue'.tr,
            gain,
            ResKey.yuan.tr,
            '',
            isHome: true,
          ),
          // Container(
          //   // padding: EdgeInsets.only(left: 12.w,right: 12.w),
          //   height: 66,
          //   decoration: BoxDecoration(
          //       borderRadius: BorderRadius.circular(10),
          //       color: Colour.backgroundF5F5F7Color),
          //   alignment: Alignment.center,
          //   child: Column(
          //     crossAxisAlignment: CrossAxisAlignment.center,
          //     children: [
          //       Gaps.vGap14,
          //       unit.toString() != '¥'?Text.rich(
          //         TextSpan(
          //           children: [
          //             TextSpan(
          //               text: (gain == '--' || gain.isEmpty)?gain:FormatUtil.commaSeparatedDigits(num.parse(gain)),
          //               style: dinTextStyle(
          //                   fontSize: 18,
          //                   color: Colour.mainTextColor,
          //                   fontWeight: FontWeight.w500),
          //             ),
          //             TextSpan(
          //                 text: ResKey.yuan.tr,
          //                 style: ytTextStyle(
          //                   fontSize: 11,
          //                   color: Colour.mainTextColor,
          //                 )),
          //           ],
          //         ),
          //       ),
          //       Gaps.vGap2,
          //       Text(
          //         'device.storageRevenue'.tr,
          //         textAlign: TextAlign.center,
          //         style: ytTextStyle(
          //             fontSize: 12,
          //             color: Colour.labelTextColor,
          //             fontWeight: FontWeight.normal),
          //       ),
          //     ],
          //   ),
          // ),
          // Row(
          //   children: [
          //     StatisticsItemWidget(
          //         'device.storageRevenue'.tr, gain, ResKey.yuan.tr),
          //     // Gaps.hGap10,
          //     // SizedBox(
          //     //   height: 70,
          //     //   width: (ScreenUtil().screenWidth - 42.w) / 2,
          //     // )
          //   ],
          // ),
        ],
      ),
    );
  }

  ///把电量动态添加到图表
  _addElectricityBarEChartData(String title, List originData,
      {String colorString = '#FAC958', bool isProfit = false}) {
    if (originData.isNotEmpty) {
      if (isProfit) {
        // for (var element in originData) {
        //   if(element.toString()!='null' && element.toString()!='--'){
        //     profitMaxMinList.add(num.parse(element.toString()));
        //   }
        // }
        barProfitList.add({
          'name': title,
          'type': 'bar',
          'barMaxWidth': 10,
          'itemStyle': {
            'normal': {'color': colorString, 'barBorderRadius': 11}
          },
          'data': originData
        });
      } else {
        // for (var element in originData) {
        //   if(element.toString()!='null' && element.toString()!='--'){
        //     electricityMaxMinList.add(num.parse(element.toString()));
        //   }
        // }

        state.showElectricityTitles
            .add({'title': title, 'color': colorString, 'isShow': true});
        electricityBarChartList.add({
          'name': title,
          'type': 'bar',
          'barMaxWidth': 10,
          'itemStyle': {
            'normal': {'color': colorString, 'barBorderRadius': 11}
          },
          'data': originData
        });
      }
    }
    setState(() {});
    Log.d('gain=== ' + barProfitList.toString());
  }
}
